<template>
  <el-dialog
    v-model="propsShow"
    v-bind="props.dialogOption"
    :class="[`${cssPrefix}__dialog`]"
    :modal-class="`${cssPrefix} ${mode}`"
  >
    <el-transfer
      :data="datasource"
      :props="dataProps"
      v-model="_checked"
      :titles="['客户列表', '已选择']"
      ref="transferCom"
      :class="[`${cssPrefix}__transfer`]"
      @left-check-change="
        (...args) => {
          mode === 'radio' && confirm(...args)
        }
      "
    >
      <template #default="{ option }">
        <div style="display: flex; align-items: center">
          <span>名称: {{ option?.nickName }}</span>
          <span style="margin-left: 14px">电话: {{ option?.phonenumber }}</span>
        </div>
      </template>
      <template #left-footer v-if="query.totalPage > 1">
        <el-pagination
          v-model:current-page="query.pageNum"
          :page-size="query.pageSize"
          :total="query.total"
          :pager-count="5"
          layout="prev, pager, next"
          @current-change="handleCurrentChange"
          hide-on-single-page
        ></el-pagination>
      </template>
    </el-transfer>
  </el-dialog>
</template>

<script setup>
import { ElDialog, ElTransfer, ElPagination } from 'element-plus'
import { computed, reactive, ref } from 'vue'
import api from '@/http'
const cssPrefix = 'hs-select-user'
const dataProps = {
  key: 'userId',
  label: 'nickName',
}
const emit = defineEmits()
const props = defineProps({
  modelValue: {
    default: () => [],
  },
  modelShow: {
    type: Boolean,
    default: false,
  },
  dialogOption: {
    type: Object,
    default: () => ({
      appendToBody: true,
    }),
  },
  mode: {
    type: String,
    default: 'radio',
    validator: (value) => {
      return ['radio', 'multiple'].includes(value)
    },
  },
  promiseResolve: {
    type: Function,
  },
})

const propsShow = computed({
  get() {
    return props.modelShow
  },
  set(v) {
    emit('update:modelShow', v)
  },
})

const query = reactive({
  pageNum: 1,
  pageSize: 8,
  totalPage: null,
  total: 100,
})

const handleCurrentChange = async (v) => {
  query.pageNum = v
  await generateData()
}

// 分页数据 - 保存当前页面数据
let pageData = ref([])
// 数据源 - 保存已选中项以及当前页面数据
let datasource = ref([])
// 选中项 - // 外部传入数据回显 + 内部所有选中数据回显
const checked = ref([...Array.prototype.concat.call(props.modelValue || [])])
// 选中项代理 处理v-model
const _checked = computed({
  get() {
    return checked.value.map((item) => item?.[dataProps.key]).filter((item) => !!item)
  },
  async set(v) {
    checked.value = v.map((item) => datasource.value.find((ele) => ele[dataProps.key] === item))
    await generateData()
  },
})

const generateData = () => {
  pageData.value.forEach((item) => {
    const index = datasource.value.findIndex((el) => el[dataProps.key] === item[dataProps.key])
    const checkIndex = checked.value.findIndex((el) => el[dataProps.key] === item[dataProps.key])
    if (index < 0 && checkIndex !== -1) {
      datasource.value.push(item)
    } else if (index !== -1 && checkIndex === -1) {
      datasource.value.splice(index, 1)
    }
  })
  for (let i = 0; i < datasource.value.length; i++) {
    const item = datasource.value[i]
    const checkIndex = checked.value.findIndex((el) => el[dataProps.key] === item[dataProps.key])
    if (checkIndex === -1) {
      datasource.value.splice(i, 1)
      i--
    }
  }
  api.enterprise.clientList(query).then((result) => {
    result = result.data || {}
    query.total = result.total || 0
    query.pageNum = result.pageNum || 1
    query.pageSize = result.pageSize || 10
    query.totalPage = result.totalPage || 1
    pageData.value = result.list || []
    pageData.value.forEach((item) => {
      if (datasource.value.findIndex((el) => el[dataProps.key] === item[dataProps.key]) < 0) {
        datasource.value.push(item)
      }
    })
  })
}

generateData()

const confirm = (v) => {
  let result
  if (props.mode === 'radio') {
    _checked.value = v
  }
  result = props.mode === 'radio' ? checked.value[0] : checked.value
  emit('update:modelValue', result)
  props.promiseResolve && props.promiseResolve(result)
  propsShow.value = false
}
</script>

<script>
export default {
  name: 'hs-select-user',
}
</script>

<style lang="scss">
$prefix: 'hs-select-user';

.#{$prefix} {
  &__dialog {
    width: 940px;
  }
  &.radio &__dialog {
    width: 408px;
  }
  &.radio &__transfer {
    > * {
      display: none;
    }
    .el-transfer-panel:nth-child(1) {
      display: block;
    }
    .el-transfer-panel__header {
      .el-checkbox__input {
        display: none;
      }
      .el-checkbox__label {
        padding: 0;
        > span {
          display: none;
        }
      }
    }
  }
  &__transfer {
    .el-transfer-panel {
      width: 352px;
    }
    .el-transfer-panel__item {
      height: auto;
    }
  }
}
</style>
